<template>
    <div class="search-his">
        <h3>搜索历史</h3>
        <div
            v-for="item,index in hisList"
            :key="item"
            @click="pushKeyword(item)"
            :style="randomColor(index)">
            {{item}}
        </div>
    </div>
</template>

<script>
export default {
    name: 'searchHistory',
    props: {
        keyword: String,
    },
    data() {
        return {
            hisList : [],
            hisSet : new Set(),
        }
    },
    methods: {
        // 发送点击的搜索历史
        pushKeyword(word){
            this.$emit('changeKeyword',word)
        },
        //随机颜色（深）
        randomColor(index) {
            let c = 'rgb('+this.randomNum(0,100)+','+this.randomNum(0,100)+','+this.randomNum(0,100)+')';
            let fontC = index >3 ? c : 'white';
            let bgC = index >3 ? 'transparent' : c;
            let bor = c;
            return {
                'color':fontC,
                'background':bgC,
                'border-color': bor
            }
        },
        //返回范围内的数字 左闭右开
        randomNum(mini,maxi) {
            return Math.floor(Math.random()*(maxi-mini)) +(mini);
        }
    },
    mounted() {
        var searchHis = JSON.parse(localStorage.getItem('searchHis'));
        // console.log(searchHis);
        if(searchHis != null) {
            this.hisList = searchHis;
            this.hisSet = new Set(this.hisList);
        }
    },
    watch: {
        keyword(newv,oldv) {
            // 添加新的搜索记录，并放入localStorage里
            if(newv != undefined && newv.length > 0) {
                if(this.hisSet.has(newv)){
                    this.hisList.splice(this.hisList.findIndex(e => e === newv), 1);
                    this.hisList.unshift(newv);
                    localStorage.setItem('searchHis',JSON.stringify(this.hisList));
                }
                else {
                    this.hisSet.add(newv);
                    this.hisList.unshift(newv);
                    if(this.hisList.length > 10) {
                        var ele = this.hisList.pop();
                        this.hisSet.delete(ele);
                    }
                    localStorage.setItem('searchHis',JSON.stringify(this.hisList));
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.search-his {
    padding: 10px 15px;
    h3 {
        font-size: 20px;
        margin-bottom: 10px;
    }
    div {
        display: inline-block;
        margin: 5px;
        padding: 3px 20px;
        font-size: 18px;
        border: 1px solid;
        border-color: black;
        border-radius: 5px;
    }
}
</style>